package cn.com.cym.gamezao.web.demo;

import cn.com.cym.gamezao.entity.single.VaccineReg;
import cn.com.cym.gamezao.service.single.VaccineRegService;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags = "导出")
@RestController
@RequestMapping(value = "export")
public class ExportController {

    final VaccineRegService thisService;

    public ExportController(VaccineRegService thisService){
        this.thisService = thisService;
    }


    @ApiOperation(value = "导出")
    @ApiOperationSupport(order = 1, author = "mr.chen")
    @GetMapping(name ="",produces= { MediaType.APPLICATION_OCTET_STREAM_VALUE})
    public void exportExcel(HttpServletResponse response) throws IOException {
        ExcelWriter writer = ExcelUtil.getWriter();
        List<VaccineReg> vaccineRegs = thisService.getAll();

        List<Map<String, Object>> rows = vaccineRegs.stream().map(item -> {
            Map<String, Object> maps = new HashMap<>();
            maps.put("id", item.getId().toString());
            maps.put("name", item.getUserName());
            maps.put("age", item.getAge());
            maps.put("sex", item.getSex());
            maps.put("createTime", item.getCreateTime().toString());
            return maps;
        }).collect(Collectors.toList());

        // Header
        writer.addHeaderAlias("id", "ID");
        writer.addHeaderAlias("name", "姓名");
        writer.addHeaderAlias("age", "年龄");
        writer.addHeaderAlias("sex", "性别");
        writer.addHeaderAlias("createTime", "登记时间");

        // Body
        writer.write(rows, true);

        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("登记信息-" + DateUtil.today() + ".xls", "utf-8"));

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
    }
}
